<template>
  当前拦截返回已开启{{open}}
  <button @click="historyRecord(true)" >开启</button>
  <button @click="historyRecord(false)" >关闭</button>
</template>

<script setup>
  import {onBeforeUnmount, ref} from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'

  let open = ref(false)

  // 拦截逻辑
  function intercept(event) {
    // 需要拦截
    if(open.value) {
      // 阻止页面默认行为（后退）
      event.preventDefault()

      // 使用交互诱导用户点击，以免二次返回不生效
      ElMessageBox.confirm(
        '确定返回页面?',
        '提示',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }
      )
        .then(() => {
          open.value = false
          history.back()
        })
        .catch(() => {
          history.pushState({ id: 'stopBack' }, '', window.location.href);
          ElMessage({
            type: 'success',
            message: '拦截成功',
          })
        })
    }
  }

  // 开启或关闭拦截功能
  function historyRecord(flag) {
    if(flag && !open.value) {
      open.value = true
      history.pushState({ id: 'stopBack' }, '', window.location.href);
    } else if(!flag && open.value) {
      open.value = false
      history.back()
    }
  }

  // 注册
  window.addEventListener('popstate', intercept)

  // 卸载前解绑
  onBeforeUnmount(() =>{
    window.removeEventListener('popstate', intercept)
  })


  
</script>